package com.omg.weibo;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;
import java.util.ResourceBundle;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.multipart.ByteArrayPartSource;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.PartSource;
import org.apache.commons.httpclient.methods.multipart.StringPart;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.omg.server.util.CommonUtil;
import com.omg.server.util.PropertiesHelper;

public class WeiBoSender {
	private static HttpClient client = new HttpClient();
	private static final Log log = LogFactory.getLog(WeiBoSender.class);
	public void send(String title, String imageUrl, String targetUrl){
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			log.error(e);
		}
		this.SinaWeiBoSender(title, imageUrl, targetUrl);
		QQWeiBoSender.send(title, imageUrl, targetUrl);
	}
	
	public void SinaWeiBoSender(String title, String imageUrl, String targetUrl){
		try{
			String authUrl = PropertiesHelper.getProperty("authorizeURL");
		    String accesscodeUrl = PropertiesHelper.getProperty("accesstokenURL");
			String clientId = PropertiesHelper.getProperty("client_ID");
			String redirect_uri = PropertiesHelper.getProperty("redirect_URI");
			String authCode = null;
	
			PostMethod postMethod = new PostMethod(authUrl); 
			postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			postMethod.addRequestHeader("Referer", authUrl);
			postMethod.addRequestHeader("Host", "api.weibo.com");
			postMethod.addParameter("client_id", clientId); //appkey 
			postMethod.addParameter("redirect_uri", redirect_uri);   //oauth2 回调地址   
			postMethod.addParameter("response_type", "code");//请求code信息         
			postMethod.addParameter("action", "submit");//表示授权访问         
			postMethod.addParameter("userId", "buymefan@126.com");  //微博帐号         
			postMethod.addParameter("passwd", "bmf_admin");  //帐号密码       
			
			client.executeMethod(postMethod);
			Header header = postMethod.getResponseHeader("Location");
			if (null != header){
				String authCodeUrl = header.getValue();
				if (null != authCodeUrl){
					int index = authCodeUrl.indexOf("?");
					int len = authCodeUrl.length();
					if (index > -1 && len > (index+1)){
						authCodeUrl = authCodeUrl.substring(index+1, authCodeUrl.length());
						authCode = parseQueryString(authCodeUrl);
					}
				}
				
			}
			
			//System.out.println("authCode = " + authCode);
			postMethod.releaseConnection();
			if(CommonUtil.isNotEmpty(authCode)){
				postMethod = new PostMethod(accesscodeUrl); 
				postMethod.addParameter("client_id", clientId);     //appkey    
				postMethod.addParameter("client_secret", PropertiesHelper.getProperty("client_SERCRET"));   //appsecret 
				postMethod.addParameter("grant_type", "authorization_code");      
				postMethod.addParameter("code", authCode);        //上一步骤拿到的code  
				postMethod.addParameter("redirect_uri", redirect_uri);   //回调地址
				client.executeMethod(postMethod);
				String result = postMethod.getResponseBodyAsString();      
		        JSONObject jsonObject = new JSONObject(result);     
		        String access_token = jsonObject.getString("access_token");//获取到的access_token 
		        //sendWeiBo(access_token, "自动发送without图片", null);
		        String content = title+ " 详情面面 " + targetUrl;
		        sendWeiBo(access_token, content, imageUrl);
				postMethod.releaseConnection();
			}
		}
		catch(Exception e){
			log.error(e);
		}
	}
	
	private String parseQueryString(String params){
		String authCode = null;
		if (CommonUtil.isNotEmpty(params)){
			String[] nameValue = params.split("&");
			String[] values = null;
			for (String val : nameValue){
				values = val.split("=");
				if ("code".equals(values[0]) && values.length > 1){
					authCode = values[1];
					break;
				}
			}
		}
		return authCode;
	}
	
	public void sendWeiBo(String accessToken, String content, String imgUrl){
		
	   //图片和内容上传设置
        PostMethod postMethod = null;
        if (CommonUtil.isNotEmpty(imgUrl)){
        	postMethod = new PostMethod(PropertiesHelper.getProperty("sendWeiBoWithPicUrl")); 
        	List<Part> parts = new ArrayList<Part>();
     	    parts.add(new StringPart("access_token", accessToken, "utf-8"));
     	    parts.add( new StringPart("status", content, "utf-8"));
        	//图片上传
    		byte[] imgContent = readFromURL(imgUrl);
    		if (null != imgContent && imgContent.length > 0){
    			PartSource ps = new ByteArrayPartSource("test", imgContent); 
    			parts.add(new FilePart("pic", ps, "multipart/form-data", "utf-8"));
    			Part[] results = new Part[parts.size()];
		        parts.toArray(results);
		        RequestEntity requestEntity = new MultipartRequestEntity(results, postMethod.getParams());
		        postMethod.setRequestEntity(requestEntity);
    		}
        }
        else{
        	postMethod = new PostMethod(PropertiesHelper.getProperty("sendWeiBoUrl"));
        	postMethod.addParameter("access_token", accessToken);
        	postMethod.addParameter("status", content);
        }
        
        postMethod.addRequestHeader("Accept-Language", "zh-CN,zh;q=0.8");  
        postMethod.addRequestHeader("User-Agent", "IE7");  
        postMethod.addRequestHeader("Accept-Charset", "utf-8;q=0.7,*;q=0.3");  
        postMethod.getParams().setContentCharset("utf-8"); 
		
       
        
        JSONObject jsonObject = null;
        try {
			client.executeMethod(postMethod);
			String result = postMethod.getResponseBodyAsString(); 
		    jsonObject = new JSONObject(result); 
	    }
        catch (Exception e) {
	        e.printStackTrace();
	    }
        if (null != jsonObject){
        	System.out.println(jsonObject);
        }
        postMethod.releaseConnection();
        System.out.println("发送完毕");
	}
	
	public static byte[] readFromURL(String url) {  
        GetMethod getMethod = new GetMethod(url);  
        // 加入同步避免被防盗链机制屏蔽而取不到内容  
        Header h = new Header("referer", "hupan.com");  
        getMethod.setRequestHeader(h);  
        getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());  
        try {  
           // 执行getMethod  
           int statusCode = client.executeMethod(getMethod);  
           if (statusCode != HttpStatus.SC_OK) {  
                 return new byte[] {};  
           }  
           // 读取内容  
           byte[] responseBody = getMethod.getResponseBody();  
           // 处理内容  
           return responseBody;  
        } 
        catch (Exception e) {  
            System.err.println("读取url失败：url->" + url + ":" + e);  
            return new byte[] {};  
        }
        finally {  
            // 释放连接  
            getMethod.releaseConnection();  
       }  
	}  

       


	
	public static void main(String[] args) throws NoSuchAlgorithmException, KeyManagementException, IOException{
		ResourceBundle bundle = ResourceBundle.getBundle("META-INF.config.env.application");
		Properties props = new Properties();
	    Enumeration<String> enums = bundle.getKeys();
	    String key = null;
	    String value = null;
	    while (enums.hasMoreElements()) {
	      key = enums.nextElement();
	      value = bundle.getString(key);
	      props.put(key, value);
	    }
	    //默认加载application.properties并存在内存中
	    PropertiesHelper.initDefaultProps(props);
		new WeiBoSender().send("测试","http://img01.taobaocdn.com/bao/uploaded/i1/T1Az5bXXNAXXb7uCUY_030547.jpg_310x310.jpg","www.bumefan.com/1");
	}
		
}
